package com.bjpowernode.web;

import com.bjpowernode.model.TUser;
import com.bjpowernode.query.UserQuery;
import com.bjpowernode.result.R;
import com.bjpowernode.service.UserService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


@RestController
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 获取登录人信息
     * @param authentication:框架限制了数据传递，spring security提供的包含了用户信息的参数
     * @return R
     */
    @GetMapping(value = "/api/login/info")
    public R loginInfo(Authentication authentication) {
        TUser tUser = (TUser) authentication.getPrincipal();//由于被security封装了，只可以用这种方式获得用户（还是基于session）但是前后端分离是禁用session的，vue无法保持状态，前端只会提示你登录，不会拿到信息
        return R.OK(tUser);
    }

    /**
     * 免登录   工具人了，无参无数据，就是对免登录请求的回应，能走到这一步，就已经校验过token合法了，直接让通过就好，不用过多处理
     * @param :
     * @return R
     */
    @GetMapping(value = "/api/login/free")
    public R freeLogin() {
        return R.OK();
    }

    //查询用户分页
    @GetMapping("/api/users")
    public R userPage(@RequestParam(value = "current",required = false) Integer current){
        //required = false 表示参数可传可不传
        //required = true 表示参数必须传，不然会报错
        if (current == null){
            current = 1;
        }
        PageInfo<TUser> pageInfo = userService.getUserByPage(current);
        return R.OK(pageInfo);
    }

    @GetMapping("/api/user/{id}")
    public R userDetail(@PathVariable(value = "id") Integer id){
        TUser tUser = userService.getUserById(id);
        return R.OK(tUser);
    }

    /**
     * 新增用户
     *
     * @param userQuery
     * @return
     */
    @PostMapping(value = "/api/user")
    public R addUser(UserQuery userQuery, @RequestHeader(value = "Authorization") String token) {
        userQuery.setToken(token);
        int save = userService.saveUser(userQuery);
        return save >= 1 ? R.OK() : R.FAIL();
    }

    /**
     * 编辑用户
     *
     * @param userQuery
     * @return
     */
    @PutMapping (value = "/api/user")
    public R editUser(UserQuery userQuery, @RequestHeader(value = "Authorization") String token) {
        userQuery.setToken(token);
        int update = userService.updateUser(userQuery);
        return update >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value = "/api/user/{id}")
    public R delUser(@PathVariable(value = "id") Integer id){
        int del = userService.delUserById(id);
        return del >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value = "/api/user")
    public R batchDelUser(@RequestParam(value = "ids") String ids){
        List<String> idList = Arrays.asList(ids.split(","));
        int batchDel = userService.batchDelUserById(idList);
        return batchDel >= idList.size() ? R.OK() : R.FAIL();
    }
}
